﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ext.Net;
using Enterprise.Data.Dynamic;
using System.Reflection;
namespace Enterprise.Web.Controls
{
    public class XTreePanel:TreePanel
    {
        public XTreePanel()
        { 
            this.BuildTopBar();
        }

        private Toolbar mToolbar;
        TriggerField trigger;
        private void BuildTopBar()
        {
            mToolbar =new Toolbar();
            ToolbarTextItem lbl =new ToolbarTextItem();
            lbl.Text="Tìm kiếm";
            mToolbar.Items.Add(lbl);
            mToolbar.Items.Add(new ToolbarSpacer());
            trigger = new TriggerField();
            trigger.EnableKeyEvents = true;
            mToolbar.Items.Add(trigger);
            FieldTrigger fieldTrigger = new FieldTrigger();
            fieldTrigger.Icon = TriggerIcon.Clear;
            trigger.Triggers.Add(fieldTrigger);           
            trigger.Listeners.KeyUp.Buffer=250;
            
            this.TopBar.Add(mToolbar);
        }

        public void RefreshTree(string json)
        { 
            if(Ext.Net.X.IsAjaxRequest)
            {
                this.AddScript("XTreePanel.refreshTree({0},{1});", this.ClientID, json);
            }
        }

        public void RefreshTree()
        {
            if (Ext.Net.X.IsAjaxRequest)
            {
                this.AddScript("XTreePanel.refreshTree({0},{1});", this.ClientID, this.Root.ToJson());
            }
        }

        protected override void OnBeforeClientInit(Observable sender)
        {
            base.OnBeforeClientInit(sender);
            trigger.Listeners.TriggerClick.Handler = string.Format("XTreePanel.clearFilter({0},this);", this.ClientID);
            trigger.Listeners.KeyUp.Handler = string.Format("XTreePanel.filterTree({0}, this, e);", this.ClientID);

            if (!this.ResourceManager.IsClientScriptBlockRegistered("xscript.js"))
            {
                this.ResourceManager.RegisterClientScriptInclude("xscript.js", "/enterprise/resource/xscript.js", false);
            }


        }

        public string ParentID { get; set; }
        public string NodeId { get; set; }
        public string DisplayName { get; set; }
        public Ext.Net.Icon NodeIcon { get; set; }

        public string TreeNodeText { get; set; }
        public void SetDataSource(IEnumerable<object> datasource)
        {
            this.CreateTreeNode(datasource);
        }

        private void CreateTreeNode(IEnumerable<object> datasource)
        {
            //Create root node
            Ext.Net.TreeNode root = new Ext.Net.TreeNode(TreeNodeText);
            root.Expandable = ThreeStateBool.True;
            root.SingleClickExpand = false;
            root.Expanded = true;
            this.Root.Add(root);
            if (string.IsNullOrEmpty(this.ParentID)) throw new Exception("ParentID is required");
            CreateChildrenNode(0,root, datasource);
            this.RefreshTree();
        }

        private void CreateChildrenNode(int parentId, TreeNode parentNode, IEnumerable<object> datasource)
        {
            foreach (TreeNode node in GetNode(parentId, datasource))
            {
                parentNode.Nodes.Add(node);
                CreateChildrenNode(int.Parse(node.NodeID), node, datasource);
            }
        }

        private List<Ext.Net.TreeNode> GetNode(int parentId, IEnumerable<object> datasource)
        {
            PropertyInfo pParentId;
            int iParentId =0 ;
            int iNodeId = 0;
            string displayName = string.Empty;
            List<Ext.Net.TreeNode> lstNode = new List<TreeNode>();
            foreach (object obj in datasource)
            {
                pParentId = obj.GetType().GetProperty(ParentID);

                iParentId = (int)pParentId.GetValue(obj, null);
                
                if (iParentId == parentId)
                {
                    iNodeId = (int)obj.GetType().GetProperty(NodeId).GetValue(obj, null);
                    displayName = (string)obj.GetType().GetProperty(DisplayName).GetValue(obj, null);
                    lstNode.Add(NewTreeNode(iNodeId,displayName));
                }
            }
            return lstNode;
        }

        private TreeNode NewTreeNode(int nodeId, string displayName)
        {
            return new Ext.Net.TreeNode(nodeId.ToString(), displayName, this.NodeIcon);
        }       
    }
}
